import React, { Component, Fragment } from 'react';
import { connect } from 'dva';
import { Spin, Form, Radio, Button, Modal } from 'antd';
import router from 'umi/router';
import moment from 'moment';
import EditPage from '@/components/EditPage';
import DetailPage from '@/components/DetailPage';
import FileReader from '@/components/FileReader';
import { formItemFragement, queryDict, formatPrice } from '@/utils/common';
import { allDictList } from '@/utils/constans';
import OcrPaperList from './OcrPaperListInfo';
import AntdForm from '@/components/AntdForm';
import AntdInput from '@/components/AntdInput';
import AntdFormItem from '@/components/AntdFormItem';
import AdButton from '@/components/AdButton';
import prompt from '@/components/Prompt';
import {
  ocrCompanyList, ocrVDList,
  selectOcrList,
  renderTableAdSelect,
  renderTableAdSearch,
  allDispatchType,
  formateNOSecond,
  allUrl,
  ocrTypeList,
  statusList,
  codes,
  selectDetail,
  routeUrl
} from './utils';
const confirm = Modal.confirm;

@Form.create()
@connect(({ paperVerify, component, loading }) => ({
  ocrDetails: paperVerify.ocrDetails,
  dictObject: component.dictObject,
  searchValue: component.searchValue,
  loading: loading.effects[allDispatchType.detail],
}))
export default class PaperVerifyDetail extends Component {
  constructor(props) {
    super(props)
    this.state = {
      detailId: '',
      auditType: 'PASS',
      visible: false,
      showUpload: true,
    };
  }


  componentDidMount() {
    // const { id } = this.props;
    const {
      match: {
        params: { id },
      },
    } = this.props;
    this.handleStateChange([{ detailId: id }]);
    id && selectDetail({
      type: allDispatchType.detail,
      payload: { id },
      props: this.props
    })
  }

  handleStateChange = (options = []) => {
    options.map(item => {
      this.setState(item);
    });
  };

  auditInfo = () => {
    const { loading, ocrDetails, form: { getFieldDecorator } } = this.props;
    const { detailId, auditType } = this.state;
    const detail = ocrDetails[detailId] || {};
    const disabled = detail.status === 'DRAFT'
    const auditDisabled = detail.status === 'FINISH'

    const commonParams = {
      getFieldDecorator,
    };
    const formItem = [
      [
        <AntdFormItem
          label="审核结果"
          code="status"
          initialValue={detail.audit}
          rules={[{ required: true }]}
          {...commonParams}
        >
          <Radio.Group
            onChange={e => {
              this.handleStateChange([{ auditType: e.target.value }]);
            }}
          >
            <Radio value="PASS" disabled={auditDisabled}>
              通过
            </Radio>
            <Radio value="REFUSE" disabled={auditDisabled}>
              退回
            </Radio>
          </Radio.Group>
        </AntdFormItem>,
      ],
      [
        <AntdFormItem
          label="备注"
          code="remarks"
          initialValue={detail.remarks}
          {...commonParams}
          rules={[{ required: auditType !== 'PASS' }]}
        >
          <AntdInput type="textarea" rows={4} disabled={auditDisabled} />
        </AntdFormItem>,
      ],
    ]
    return <div>
      <AntdForm>{formItemFragement(formItem)}</AntdForm>
    </div>
  }
  infoAdd = e => {
    e.stopPropagation();
    this.setInfoModal('');
    this.handleStateChange([
      { papersId: '', papersType: '', showUpload: true }
    ])
  };
  setInfoModal = () => {
    this.setState((pre) => ({
      visible: !pre.visible
    }))
  };
  //  审核
  auditOcr = () => {
    const { form, dispatch, formValues } = this.props;
    form.validateFieldsAndScroll((errors, values) => {
      if (!values.status) prompt({ type: 'warn', content: '请选择审核结果' })
      if (errors) return;
      this.handleOcr('auditOcr', values, '确认审核？');
    });
  };
  //OCR操作:
  handleOcr = (type, params, tips) => {
    confirm({
      title: tips ? tips : type == 'delOcr' ? '确定要删除这条数据吗？' : '提交后将不能编辑，确定提交？',
      content: ' ',
      okText: '确定',
      okType: type == 'delOcr' ? 'danger' : '',
      cancelText: '取消',
      onOk: () => {
        this.dispatchOcr(type, params);
      },
    });
  };
  dispatchOcr = (type, params = {}) => {
    const { dispatch, formValues } = this.props;
    const { detailId } = this.state;
    params.id = detailId;
    dispatch({
      type: allDispatchType[type],
      payload: params,
      callback: data => {
        // if (!data) return;
        selectOcrList({ props: this.props, payload: formValues });
        if (type == 'delOcr') {
          router.push(`${routeUrl.list}`)
        } else {
          detailId && selectDetail({
            type: allDispatchType.detail,
            payload: { id: detailId },
            props: this.props
          })
        }

      },
    });
  }

  headerOperate = () => {
    const {
      ocrDetails,
    } = this.props;
    const { detailId } = this.state;
    const detail = ocrDetails[detailId] || {};
    const isCONFIRM = detail.status !== 'DRAFT' ? true : false;
    return (
      <div>
        <>
          <AdButton disabled={isCONFIRM} code={codes.delete} text="删除" type="danger" ghost
            onClick={() => this.handleOcr('delOcr')} style={{ marginRight: 8 }}></AdButton>
          <Button.Group>
            <AdButton
              text="提交"
              type="primary"
              code={codes.commit}
              onClick={() => this.handleOcr('commitOcr')}
              disabled={isCONFIRM}
            />
          </Button.Group>
        </>
      </div>
    );
  };

  alreadyAddPaper = (papersList) => {
    let arr = [];
    papersList && papersList.length > 0 && papersList.map((v) => {
      arr.push(v.papersType)
    })
    return arr;
  }
  render() {
    const { loading, ocrDetails } = this.props;
    const { detailId, papersId, papersType, visible, showUpload } = this.state;
    const detail = ocrDetails[detailId] || {};
    const disabled = detail.status !== 'DRAFT';
    const auditDisabled = detail.status === 'FINISH';
    const alreadyAddPaper = this.alreadyAddPaper(detail.papersList);
    const typeList = detail.type === 'COMPANY' ? ocrCompanyList : ocrVDList;
    const editPageParams = {
      title: detail.name || '',
      headerOperate: this.headerOperate(),
      panelValue: [
        { key: '基础信息' },
        {
          key: '证件信息', extra: (
            <AdButton
              disabled={disabled || typeList.length === alreadyAddPaper.length}
              type="primary"
              onClick={this.infoAdd}
              text="新增"
              code={codes.discernPaper}
            />
          ),
        },
        { key: '审核' },
      ],
    };

    const formItem = [
      [
        <DetailPage label="单号" value={detail.ocrNo} />,
        <DetailPage
          label="状态"
          value={renderTableAdSelect({
            props: this.props,
            value: detail.status,
            data: statusList,
          })}
        />,
      ],
      [
        <DetailPage
          label="类型"
          value={renderTableAdSelect({
            props: this.props,
            value: detail.type,
            data: ocrTypeList
          })}
        />,
        <DetailPage label="名称" value={detail.name} />,
      ],
    ];

    return (
      <EditPage {...editPageParams}>
        <Spin spinning={loading}>{formItemFragement(formItem)}</Spin>
        <Fragment>
          {
            detailId && <OcrPaperList
              ocrId={detailId}
              ocrType={detail.type}
              papersId={papersId}
              papersType={papersType}
              showUpload={showUpload}
              visible={visible}
              setInfoModal={this.setInfoModal}
              setStateChange={this.handleStateChange}
              disabled={disabled}
              alreadyAddPaper={alreadyAddPaper}
            />
          }

        </Fragment>
        <Fragment>
          <div>{this.auditInfo()}</div>
          <div style={{ display: 'flex', justifyContent: 'center' }}>
            <AdButton
              disabled={auditDisabled}
              type="primary"
              onClick={() => this.auditOcr()}
              text="审核"
              code={codes.audit}
            />
          </div>
        </Fragment>
      </EditPage>
    );
  }
}



